import { API, BASE_PATH } from '@/config'
import { Application, Container, Sprite, TilingSprite, Text, Graphics } from 'pixi.js'
import { sound } from '@pixi/sound'
import { useEffect, useRef, useState } from 'react'
import { AutoCenter, Button, Toast } from 'antd-mobile'
import requewt from '@/utils/requewt'
import callFeedback from '@/components/common/modalFeedback'
import { navigateTo } from '@/utils'
import { useCommonHandler } from '@/components/common/hooks'
import Router from 'next/router'
const useGameHandler = () => {
  const { gameCheck } = useCommonHandler()
  const startGame = async () => {
    const resp = await requewt(API.game.start, { method: 'post' })
    console.log(resp, 'rest')
    if (resp.error_code === 0) {
      return true
    }
    if ([1002, 1003].includes(resp.error_code)) {
      return gameCheck(resp.error_code === 1002 ? 2 : 3, () => {
        Router.replace('/landing')
      })
    }
    callFeedback({
      title: <div dangerouslySetInnerHTML={{ __html: resp?.msg }}></div>,
      hideClose: true
    })
    return false
  }
  const endGame = async (params) => {
    if (Router.pathname !== '/game') return
    const resp = await requewt(API.game.finish, { method: 'POST', body: params, headers: { 'Content-Type': 'multipart/form-data' } })
    const m = callFeedback({
      hideClose: true,
      content: <div style={{ textAlign: 'center' }}>
        <img
          src={`${BASE_PATH}/img/game/game-end.png`}
          width={91}
        />
        <div >
          <h3>恭喜您</h3>
          <p>本次游戏获得积分{resp.data?.score}分</p>
          <p>本次游戏获得U币{resp.data?.ub}</p>
        </div>
      </div>,
      actions: [
        <Button className="act-btn act-btn-bevel" key="lottery" onClick={() => {
          m.close()
          navigateTo('/rank/current')
        }}>查看排名</Button>,
        <Button className="act-btn act-btn-bevel" key="restart" onClick={() => {
          m.close()
          requewt(API.user.userGameNum).then((resp) => {
            if (resp.data?.state !== 1) {
              return gameCheck(resp.data?.state, () => {
                Router.replace('/landing')
              })
            }
            global.location.reload()
          })

        }}>继续游戏</Button>
      ]
    })
  }
  return {
    endGame,
    startGame
  }
}
const Game = () => {
  const application = useRef()
  const timer = useRef()
  const soundRef = useRef()
  const thingsRef = useRef()
  const { endGame, startGame } = useGameHandler()
  const loadSource = async () => {
    const app = new Application({
      width: global.innerWidth > 430 ? 430 : global.innerWidth,
      height: global.innerHeight,
      backgroundAlpha: 0,
      antialias: true
    })
    app.loader.add('basket', `${BASE_PATH}/img/game/basket.png`)
    app.loader.add('prize1', `${BASE_PATH}/img/game/prize-1.png`)
    app.loader.add('prize2', `${BASE_PATH}/img/game/prize-2.png`)
    app.loader.add('prize3', `${BASE_PATH}/img/game/prize-3.png`)
    app.loader.add('prize4', `${BASE_PATH}/img/game/prize-4.png`)
    app.loader.add('prize5', `${BASE_PATH}/img/game/prize-5.png`)
    app.loader.add('prize6', `${BASE_PATH}/img/game/prize-6.png`)
    app.loader.add('process', `${BASE_PATH}/img/game/game-precess.png`)
    sound.add('sound', `${BASE_PATH}/audio/happyrock.mp3`)
    sound.add('things', `${BASE_PATH}/audio/things.mp3`)
    app.loader.onComplete.add(() => {
      // console.log('加载完')
      // Toast.show({ content: `加载完成`, duration: 1000 })
    })
    app.loader.load()
    application.current = app
    return app
    // app.stage.addChild(player)


  }
  const renderGame = (app) => {
    if (!app) return
    document.getElementById('game').appendChild(app.view)
    sound.play('sound')
    const player = new Sprite(app.loader.resources[`basket`].texture)
    console.log(player.width)
    player.scale.set(app.renderer.width / player.width / 2.2)
    player.x = app.renderer.width / 2 - player.width / 2
    player.y = app.renderer.height * 0.85
    player.interactive = true
    player.buttonMode = true
    let score = 0
    let ub_num = 0
    // 添加拖动事件
    player.on('pointerdown', onDragStart)
      .on('pointerup', onDragEnd)
      .on('pointerupoutside', onDragEnd)
      .on('pointermove', onDragMove);

    let isDragging = false;
    let startX = 0;

    function onDragStart(event) {
      // 记录拖动开始时的坐标
      isDragging = true;
      startX = event.data.global.x - player.x;
    }

    function onDragEnd() {
      // 拖动结束时清除拖动数据
      isDragging = false;
    }

    function onDragMove(event) {
      // 在拖动时更新精灵的位置，但只允许水平移动
      if (isDragging) {
        const newPositionX = event.data.global.x - startX;
        player.x = Math.min(Math.max(newPositionX, 0), app.renderer.width - player.width);
        // 上述代码限制了玩家的水平移动范围在画布内，避免越过边界
      }
    }
    // 创建物品数组，包含6种不同的物品
    const items = [{
      name: 'prize1',
      score: 0,
    }, {
      name: 'prize2',
      score: 5
    }, {
      name: 'prize3',
      score: 5,
    }, {
      name: 'prize4',
      score: 5
    }, {
      name: 'prize5',
      score: 5
    }, {
      name: 'prize6',
      score: -10
    }];
    // 碰撞检测函数
    function isPlayerIntersecting(item, player) {
      return (
        item.x < player.x + player.width &&
        item.x + item.width > player.x &&
        item.y < player.y + player.height &&
        item.y + item.height > player.y
      );
    }
    // 创建游戏进度条
    const progressBar = new TilingSprite(app.loader.resources[`process`].texture, app.renderer.width * 0.8, 10);
    progressBar.y = 0; // 设置进度条的垂直位置
    const progressContainer = new Container()
    progressContainer.height = 10
    progressContainer.width = 200
    progressContainer.y = app.renderer.height * 0.95
    // progressContainer.x = app.renderer.width * 0.2

    // progressContainer.
    const progress = new Graphics()
    progress.beginFill(0xFFFFFF)
    progress.drawRoundedRect(app.renderer.width * 0.2 / 2, 0, app.renderer.width * 0.7, 10, 5)
    // 创建文本对象用于显示秒数
    const timerText = new Text('', { fontFamily: 'Arial', fontSize: 24, fill: 0xffffff });
    timerText.x = app.renderer.width - 60; // 设置文本的横向位置
    timerText.y = -10; // 设置文本的纵向位置
    // progressContainer.addChild(timerText);
    // progressContainer.addChild(progress)
    progressBar.y = progress.y
    progressBar.x = app.renderer.width * 0.2 / 2
    // console.log(progressBar.x)
    progressBar.width = 0
    progressContainer.addChild(progress, progressBar, timerText)
    // app.stage.addChild()
    app.stage.addChild(progressContainer)
    // app.stage.addChild(timerText)
    // 游戏总时间
    const gameDuration = Date.now() + 25 * 1000; // 25秒
    let gameTime = 0;
    const scoreContainer = new Container()
    const scoreText = new Text('分数：0分', { fontSize: 24, fill: 0x054a74 })
    // 创建白色背景
    // 创建白色背景带有圆角
    const backgroundRect = new Graphics();
    backgroundRect.beginFill(0xFFFFFF); // 白色背景
    backgroundRect.drawRoundedRect(0, 0, 170, 40, 20); // 圆角矩形，20是圆角的半径
    backgroundRect.endFill();
    // 设置文本水平垂直居中
    scoreText.x = (backgroundRect.width - scoreText.width) / 2 + 4;
    scoreText.y = (backgroundRect.height - scoreText.height) / 2;
    // 设置分数容器水平居中
    console.log(scoreContainer.width)
    scoreContainer.x = (app.renderer.width - backgroundRect.width) / 2;
    scoreContainer.y = 20
    scoreContainer.addChild(backgroundRect, scoreText)
    app.stage.addChild(scoreContainer)


    // 更新游戏进度条
    function updateProgressBar() {
      // console.log(1)
      console.log(backgroundRect.width / 750, app.renderer.width / 2000)
      progressBar.width += app.renderer.width / 2100
      // console.log(progressBar.width)
      // 更新文本显示秒数
      timerText.text = `${Math.ceil(((gameDuration - Date.now()) / 1000))}s`;
    }
    let collidedItems = []; // 标记是否检测到碰撞
    // 创建一个定时器，每500毫秒生成一个物品
    timer.current = setInterval(() => {
      // 随机选择一个物品
      const randomItem = items[Math.floor(Math.random() * items.length)];

      // 创建物品精灵
      const newItem = new Sprite(app.loader?.resources[randomItem.name].texture);
      newItem.name = randomItem.name
      newItem.score = randomItem.score
      newItem.scale.set(0.5)
      // 设置物品精灵的初始位置
      // 设置物品精灵的初始位置
      newItem.x = Math.random() * (app.renderer.width - newItem.width);
      newItem.y = -newItem.height; // 初始位置在屏幕顶部之外

      // 将物品精灵添加到舞台
      app.stage.addChild(newItem);

      // 使用app.ticker.add注册每帧的回调函数
      app.ticker.add(() => {
        // 在每帧中检测碰撞
        if (!collidedItems.includes(newItem) && isPlayerIntersecting(newItem, player)) {
          if (newItem.name === 'prize1') {
            ub_num += 1
          } else {
            scoreText.text = `分数：${score + newItem.score > 0 ? score += newItem.score : 0}分`

          }
          sound.play('things', { loop: false })
          // 在这里可以添加处理玩家接住物品的逻辑
          // 移除物品精灵
          app.stage.removeChild(newItem);
          collidedItems.push(newItem)
        }

        // 物品下落动画
        newItem.y += 5; // 调整下落速度

        // 如果物品超出底部边界，移除物品精灵
        if (newItem.y > app.renderer.height) {
          app.stage.removeChild(newItem);
          collidedItems = collidedItems.filter(item => item !== newItem)
        }
      });
    }, 500);
    // 每帧更新游戏时间和进度条
    app.ticker.add(() => {
      updateProgressBar();

      // // 如果游戏时间超过总时间，结束游戏
      if (Math.ceil(((gameDuration - Date.now()) / 1000)) <= 0) {
        app.ticker.stop()
        sound.removeAll()
        endGame({ score, ub_num })
      }
    });
    const container = new Container()
    container.addChild(player)
    application.current.stage.addChild(container)
  }
  useEffect(() => {
    (async () => {
      await Toast.show({ icon: `loading`, content: `游戏加载中`, duration: 0, maskClickable: false })

      const app = await loadSource();

      app.loader.onComplete.add(e => {
        // renderGame(app);
        Toast.show({ content: `加载完成`, duration: 1000 })
        const m = callFeedback({
          body: 'act-feedback-modal share-modal  close-at-center-bottom',
          // title: ,
          hideClose: true,
          content: <div style={{ textAlign: 'center' }}>
            <div className='title' style={{ lineHeight: 2, fontWeight: 'bold', fontSize: '1.8rem' }}>游戏道具</div>
            <img
              src={`${BASE_PATH}/img/game/game-tips.png`}
              width={206}
            />
          </div>,
          actions: <Button className="act-btn act-btn-bevel" onClick={() => {
            m.close()
            startGame().then((result) => {
              if (result) renderGame(app)

            })

          }}>确定</Button>
        })

      })

    })()
    return () => {
      // application.current.r
      // console.log(application.current)
      clearInterval(timer.current)
      application.current?.destroy()
      sound?.removeAll()
    }
  }, [])
  useEffect(() => {
    // setTimeout(() => {
    //   startGame()
    // }, 1000);
  }, [])
  return (
    <div id="game">

    </div>
  )
}
export default Game